<template>
    <div class="box">
        <MainContent v-bind:name="'新闻池'">
            <el-card class="card flex-1 w-full" style="overflow: auto;" header-class="px-0 pt-[2vh] pb-0 flex flex-col"
                body-class="p-0" footer-class="p-0 pt-[2vh] pb-[7vh]">
                <template #header style="padding: 0;">
                    <el-form-item label="新闻内容:">
                        <el-input v-model="filterData.keywords" class="responsive-input" placeholder="请输入文章摘要和标题"
                            style="width:20vw;height: 3vh;" label="新闻内容" />
                    </el-form-item>
                    <ul class="flex typeList mb-[2vh]">
                        <p>新闻类型:</p>
                        <li v-for="item in typeList"
                            v-bind:class="{ 'active': item.classReal === filterData.classReal }"
                            @click="filterData.classReal = item.classReal">{{ item.cn }}({{
                                item.count
                            }})</li>
                    </ul>
                    <ul class="flex typeList mb-[2vh]">
                        <p>筛选条件:</p>
                        <div>dirty code</div>
                        <li v-for="item in filterList" class="flex">
                            <el-dropdown v-on:command="command => { filterData[item.key] = command; item.active = true; }">
                                <span class="outline-none flex leading-6" v-bind:class="{ 'active': item.active }">
                                    {{ item.cn }}
                                    <el-icon class="el-icon--right mt-[0.3vh]">
                                        <arrow-down />
                                    </el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item v-for="it in item.children" :command="it.value"
                                            v-on:click="item.active = true">
                                            {{ it.cn }}
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </li>
                    </ul>
                </template>
                <ul class="newsList">
                    <li class="py-[1vh] border-dashed border-[1px] text-center mt-[2vh] mb-[1vh] rounded-md">
                        <el-icon class="pt-[0.2vh] mr-[1vw]">
                            <Plus />
                        </el-icon>
                        <span class="cursor-pointer" @click="showAddNews = true" >手动添加新闻</span>
                    </li>
                    <li class="flex flex-col pt-[2vh] border-b-[1px]" v-for="item in newsList">
                        <NewsItem v-bind:data="item" @removeData="removeData" @addData="addData" @edit="handleEdit"/>
                    </li>
                </ul>
                <template #footer>
                    <el-pagination background layout="prev, pager, next" :total="typeList[0].count" class="float-right"
                        v-model:current-page="current" />
                </template>
            </el-card>
            <el-card class="card ml-[1vw] pr-0 flex flex-col" style="width: 23vw;"
                header-class="px-0 pt-[2vh] pb-[2.5vh]  pb-0 flex flex-col border-0 font-bold"
                body-class="p-0 overflow-y-auto overflow-x-hidden flex-1 " footer-class="p-0  pt-[2vh]
                pb-[2vh] pr-[1vw] shrink-0">
                <template #header>
                    <span class="font-semibold">待发布新闻({{ releaseList.length }})</span>
                </template>
                <ReleaseList v-if="releaseList.filter(item => item.classReal === 1).length"
                    v-bind:data="{ name: '宏观形势', list: releaseList.filter(item => item.classReal === 1) }"
                    @removeData="removeData" />
                <ReleaseList v-if="releaseList.filter(item => item.classReal === 2).length"
                    v-bind:data="{ name: '行业动态', list: releaseList.filter(item => item.classReal === 2) }"
                    @removeData="removeData" />
                <ReleaseList v-if="releaseList.filter(item => item.classReal === 3).length"
                    v-bind:data="{ name: '产业链动态', list: releaseList.filter(item => item.classReal === 3) }"
                    @removeData="removeData" />
                <ReleaseList v-if="releaseList.filter(item => item.classReal === 4).length"
                    v-bind:data="{ name: '国际能源观察', list: releaseList.filter(item => item.classReal === 4) }"
                    @removeData="removeData" />
                <ReleaseList v-if="releaseList.filter(item => item.classReal === 5).length"
                    v-bind:data="{ name: '其他', list: releaseList.filter(item => item.classReal === 5) }"
                    @removeData="removeData" />
                <div class="text-[#999] text-center pt-[30vh]">
                    <el-icon :size="20">
                        <Tickets />
                    </el-icon>
                    <p>请在左侧选择需要发布的新闻</p>
                </div>
                <template #footer>
                    <div v-if="releaseList.length"
                        class="rounded-md text-center h-[4vh] leading-[4vh] bg-[#3F87CF] text-[#fff] cursor-pointer" @click="goToPublishPage">发布设置</div>
                </template>
            </el-card>
        </MainContent>
        <AddNews  v-model="showAddNews" :data="data" />
    </div>
</template>

<script setup>
import { getAcounts, getNewsList, getReleaseList, updateNews } from '@/Api/newsApi';
import NewsItem from '@/Components/NewsItem.vue';
import MainContent from '@/Components/MainContent.vue';
import { onMounted, reactive, ref, watchEffect } from 'vue';
import { format } from 'date-fns';
import ReleaseList from '@/Components/ReleaseList.vue';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
import AddNews from '@/Components/AddNews.vue';

const router = useRouter();
const current = ref(1)
const newsList = ref([])

const showAddNews = ref(false)

const releaseList = ref([])
const usp = ref({})
const dirty = ref()
const typeList = reactive([
    {
        cn: '全部',
        en: 'all',
        count: 0,
        classReal: -1
    },
    {
        cn: '宏观形式',
        en: 'macroEnvironment',
        count: 0,
        classReal: 1
    },
    {
        cn: '行业动态',
        en: 'industryTrends',
        count: 0,
        classReal: 2
    },
    {
        cn: '产业链动态',
        en: 'supplyChainDynamics',
        count: 0,
        classReal: 3
    },
    {
        cn: '国际能源观察',
        en: 'internationalEnergy',
        count: 0,
        classReal: 4
    },
    {
        cn: '其他',
        en: 'other',
        count: 0,
        classReal: 5
    }
])
const filterList = ref([
    {
        cn: '时间降序',
        key: 'sortby',
        active: true,  // 默认激活
        children: [
            {
                cn: '时间降序',
                value: 0
            },
            {
                cn: '时间升序',
                value: 1
            }
        ]
    },
    {
        cn: '时间范围',
        key: 'timeRange',
        active: false,
        children: [
            {
                cn: '全部',
                value: ''
            },
            {
                cn: '一周内',
                value: `${format(new Date().setDate(new Date().getDate() - 7), 'yyyy-MM-dd')},${format(Date.now(), 'yyyy-MM-dd')}`
            },
            {
                cn: '自定义',
                value: ''
            }
        ]
    },
    {
        cn: '添加方式',
        key: 'addMode',
        active: false,
        children: [
            {
                cn: '全部',
                value: -1
            },
            {
                cn: '自动',
                value: 0
            },
            {
                cn: '人工',
                value: 1
            }
        ]
    },
    {
        cn: '发布状态',
        key: 'isPublished',
        active: false,
        children: [
            {
                cn: '全部',
                value: -1
            },
            {
                cn: '未发布',
                value: 0
            },
            {
                cn: '已发布',
                value: 1
            }
        ]
    },
])
const filterData = reactive({
    currentSize: 10,
    keywords: '',
    classReal: -1,
    addMode: -1,
    isPublished: -1,
    timeRange: '',
    sortby: 0  // 默认按时间降序排列
})

const postMes = (message, type) => {
    ElMessage({
        message: message,
        type: type,
        offset: 50,
        customClass: 'message',
        duration: 1000
    })
}

const goToPublishPage = () => {
    router.push('/post')
}

watchEffect(() => {
    usp.value = new URLSearchParams(Object.entries(filterData).reduce((obj, [key, value]) => {
        if (typeof value === 'string' && value.trim().length > 0 || typeof value === 'number' && value >= 0) {
            return {
                ...obj,
                [key]: value
            }
        } else {
            return {
                ...obj
            }
        }
    }, {}))
    console.log(usp.value.toString())
    current.value = 1
})

watchEffect(async () => {
     // 构建查询参数
     let params = usp.value.toString();
     
     // 添加分页参数
     params += '&current=' + current.value;
     
     // 添加发布状态参数
     params += '&isPublished=0';
     
     // 添加排序参数
     if (filterData.sortby !== -1) {
       params += '&sortby=' + filterData.sortby;
     }
     
     const result = await getNewsList(params);
     newsList.value = result.records;
     typeList[0].count = result.total;
})

const handleNewsClick=(newsData)=>{
    console.log(newsData)
    mode.value='read'
    selectedNewsData.value=newsData
}
const handleEdit=(newsData)=>{
    console.log(newsData)
    mode.value='edit'
    selectedNewsData.value=newsData
}

onMounted(async () => {
    const releaseResult = await getReleaseList()
    releaseList.value = releaseResult.list
    const acountResult = await getAcounts()
    typeList.map(item => item.count = acountResult[item.en] || item.count)
    dirty.value = 'dirty'
})

const removeData = async (id) => {
  try {
    // 调用API将新闻状态改为未选中（从待发布移除）
    await updateNews({
      id: id,
      isSelect: 0 // 0表示未选中（从待发布列表移除）
    })
    
    // 重新获取待发布列表（更新UI）
    const releaseResult = await getReleaseList()
    releaseList.value = releaseResult.list
    
    // 重新获取新闻池列表（显示移除的新闻）
    const listResult = await getNewsList(usp.value.toString() + '&current=' + current.value)
    newsList.value = listResult.records
    
    ElMessage.success('移除成功')
  } catch (error) {
    console.error('移除失败', error)
    ElMessage.error('移除失败')
  }
}

const addData = async (id) => {
    if (releaseList.value.length >= 10) {
        postMes('待发布数据数量超过上限', 'error')
        return
    }
    await updateNews({
        id: id,
        isSelect: 1
    })
    const releaseResult = await getReleaseList()
    releaseList.value = releaseResult.list
    const listResult = await getNewsList(usp.value.toString() + '&current=' + current.value+ '&isPublished=0')
    newsList.value = listResult.records
    postMes('添加成功', 'success')
}

</script>

<style scoped>
.box {
    width: 100%;
    overflow-x: hidden;
}

.card {
    padding: 0 1vw;
    box-sizing: border-box;
    max-height: 84vh;
}

.typeList {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    width: 100%;
}

.typeList>li {
    margin-left: 1.5vw;
    white-space: nowrap;
}

.newsList {
    width: 100%;
    overflow-x: hidden;
}

.active {
    color: #3D87CF;
    font-weight: 600;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}
.dirty {
    display: none;
}
.pr-0 {
    padding-right: 0 !important;
}

/* 响应式调整 */
@media (max-width: 1200px) {
    .typeList>li {
        margin-left: 1vw;
        font-size: 14px;
    }
}
</style>